package com.lifesea.notify.mq.handler;

import com.alibaba.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import com.alibaba.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import com.alibaba.rocketmq.common.message.MessageExt;
import com.lifesea.base.entity.PushRequest;
import com.lifesea.base.entity.PushResponse;
import com.lifesea.base.entity.ResultEnum;
import com.lifesea.commons.utils.CheckUtils;
import com.lifesea.general.facade.DeviceIdentifyFacade;
import com.lifesea.model.SysDeviceIdentify;
import com.lifesea.model.SysPushRecord;
import com.lifesea.notify.push.IPushService;
import com.lifesea.notify.push.PushFactory;
import com.lifesea.notify.service.SysPushRecordService;
import com.lifesea.rocketmq.utils.handler.MessageHandler;
import com.lifesea.rocketmq.utils.message.MessageDecoder;
import com.lifesea.rocketmq.utils.message.codec.JsonMessageDecoder;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * Push消息处理器
 */
@Component
@DependsOn({"iosPushService", "androidPushService"})
public class PushHandler implements MessageHandler<PushRequest> {

    private static final Logger logger = LoggerFactory.getLogger(PushHandler.class);

    @Autowired
    private DeviceIdentifyFacade deviceIdentifyFacade;
    @Autowired
    private SysPushRecordService pushRecordService;

    @Override
    public ConsumeConcurrentlyStatus process(PushRequest request, MessageExt message, ConsumeConcurrentlyContext context) {
        logger.info("[PUSH]接收,msgId={},request={}", message.getMsgId(), request);

        CheckUtils.checkOneNotEmty("enc、did", request.getEcn(), request.getDid());

        try {

            SysDeviceIdentify deviceIdentify;
            if (request.getDid() != null) {
                deviceIdentify = deviceIdentifyFacade.getByDidAppcode(request.getDid(), request.getAppcode().value());
            } else {
                deviceIdentify = deviceIdentifyFacade.getByEcnAppcode(request.getEcn(), request.getAppcode().value());
            }

            if (deviceIdentify == null) {
                logger.info("客户端不存在忽略 push uid={}, ecn={}, appacode={}", request.getDid(), request.getEcn(), request.getAppcode().value());
            } else {

                deviceIdentify.setIdentify(StringUtils.replace(deviceIdentify.getIdentify(), " ", ""));
                logger.info("identify={}", deviceIdentify.getIdentify());
                IPushService pushService = PushFactory.get(deviceIdentify.getOsType());

                PushResponse response = pushService.send(request, deviceIdentify);

                logger.info("push response={}", response);

                // 保存推送记录
                SysPushRecord record = new SysPushRecord();
                record.setAppcode(request.getAppcode().value());
                record.setBody(request.getBody());
                record.setCategory(String.valueOf(request.getCategory()));
                record.setCreated(new Date());
                record.setIdentify(deviceIdentify.getIdentify());
                record.setOsType(deviceIdentify.getOsType());
                record.setSucc(response.getCode() == ResultEnum.SUCCESS);
                pushRecordService.save(record);

            }
            return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
        } catch (Exception e) {
            logger.error("[PUSH]处理失败", e);
        }
        return ConsumeConcurrentlyStatus.RECONSUME_LATER;
    }

    @Override
    public MessageDecoder<PushRequest> getMessageDecoder() {
        return new JsonMessageDecoder<>(PushRequest.class);
    }

}



